﻿#ifndef TCP_CLIENT_H
#define TCP_CLIENT_H

#include "communicationprotocol.h"
#include <QDebug>
#include <QHostAddress>
#include <QObject>
#include <QTcpSocket>
#include <QTimer>
#include "pcm_towav.h"
class UPWARDPRO_EXPORT BufAnalyse : public QObject {
    Q_OBJECT

public:
    explicit BufAnalyse(QObject* parent = nullptr);
    ~BufAnalyse();
    QTimer* buf_analyse_timer;

    const QByteArray frameStart = QByteArrayLiteral("\x02\x01\x00\xFF\x55\x99\x88\xAA"); // 帧头
    //const QByteArray frameEnd = QByteArrayLiteral("\xFE\xFE"); // 帧尾 "FE FE"
    void processTempData(QByteArray data);
    void data_pcmraw(void * Sounddate);
    pcm_towav* Pcm_towav;
signals:
    void parsed_data_sig(QByteArray);
    void sn_clientIP(int SN, QHostAddress);
    void port_buf_anafinish();
    void rawdata_enough();
    void pcmtowav_finish();
    QString storage_address(QString rawpath,QString wavpath);
public slots:
    void analyseTimerStart_slot();
    void analyseTimerStop_slot();
    //void originalDataRev_slot(QHostAddress clientAddress, QByteArray);
    void dataClassification(QByteArray buf_data);
    void data_buf(QByteArray buf_data);
    void pcmtowave_slot();
private:
    QByteArray port_buf;


};

struct TcpParaTypeDef {
    QString ip;
    int port;
};
struct SoundParaTypeDef
{
    int S_frequent;//采样率
    int bit_depth;//位深
    int Channels;//声道数
};
class UPWARDPRO_EXPORT TcpClient : public CommunicationProtocol {
    Q_OBJECT
public:
    TcpClient();
    ~TcpClient();
    virtual int protocolParaInit(void* para_struct) override;

    virtual int protocolClose() override;
    virtual int protocolWrite(const QByteArray& data_buf) override;
    virtual void setProtocolReadCallbackFunc(ReceiveDataCallback callBackFunc) override;

    inline bool isIpCurrent(const QString& ip);
    static QString rawpath;
    static QString wavepath;

signals:
    void bufDataAnalyseTimerStart_sig();
    void bufDataAnalyseTimerStop_sig();
    void receivedData_sig(QByteArray data);
    void socket_reconnect();


public slots:
    void handleReceiveData_slot();
    int protocolOpen() override;
    void onError(QAbstractSocket::SocketError socketError);
private:
    QTcpSocket* m_socket = nullptr;
    QString m_ip;
    int m_port;
    bool first_analyse = true;

    ReceiveDataCallback receiveDataCallback = nullptr;
    BufAnalyse* bufAnalyse;
    QTimer* bufDataAnalyse_timer;
    QTimer* Timersocket_failconnect;
    TcpClient *tcpclient;


};
struct Sounddate{
    QByteArray sodatech1;
    QByteArray sodatech2;
    QByteArray sodatech3;
    QByteArray sodatech4;
    QByteArray sodatech5;
    QByteArray sodatech6;
    QByteArray sodatech7;
    QByteArray sodatech8;
};
#endif // TCP_CLIENT_H
